import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ParkingChargeService} from '../../service/parking-charge.service';
import {ParkingChargeQueryForm} from '../../types/req/ParkingChargeQueryForm';
import {SharedModule} from '../shared.module';
import {ParkingCharge} from '../../types/resp/ParkingCharge';
import {Page} from '../../types/page';
import {ParkingChargeAddComponent} from './parking-charge-add.component';
import {ParkingChargeViewComponent} from './parking-charge-view.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {ParkingAreaSelectorComponent} from '../parking-area/parking-area-selector.component';
import {RoomSelectorComponent} from '../room/room-selector.component';
import { exportToExcel } from '../../utils/exportUtil'


@Component({
  selector: 'parking-charge-list',
  imports: [
    ParkingAreaSelectorComponent,
    RoomSelectorComponent,
    ParkingChargeAddComponent,
    ParkingChargeViewComponent,
    SharedModule
  ],
  templateUrl: './parking-charge-list.component.html',
  standalone: true
})
export class ParkingChargeListComponent implements OnInit {
  searchForm!: FormGroup;
  searchLoading: boolean = false
  listOfData: ParkingCharge[] = [];
  total: number = 0

  @ViewChild(ParkingAreaSelectorComponent, { static: false }) parkingAreaSelectorComponent!: ParkingAreaSelectorComponent;
  @ViewChild(RoomSelectorComponent, { static: false }) roomSelectorComponent!: RoomSelectorComponent;
  @ViewChild(ParkingChargeAddComponent, { static: false }) parkingChargeAddComponent!: ParkingChargeAddComponent;
  @ViewChild(ParkingChargeViewComponent, { static: false }) parkingChargeViewComponent!: ParkingChargeViewComponent;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private parkingChargeService: ParkingChargeService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.searchForm = this.fb.group({
      parkingAreaId: [0],
      parkingAreaNumber: [''],
      residentRoomId: [0],
      residentRoomNumber: [''],
      licensePlate: [''],
    })
    this.onSearch()
  }

  onReset() {
    this.searchForm.reset()
  }

  onSearch() {
    try {
      this.searchLoading = true
      this.parkingChargeService.find(new ParkingChargeQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          const page: Page<ParkingCharge> | undefined = resp.data
          if (page && page.list.length > 0) {
            this.listOfData = page.list
            this.total = page.total
          }
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onAdd() {
    this.parkingChargeAddComponent.display(0)
  }

  onExport() {
    try {
      const headers = ['车位号','单元房号','车牌','使用开始时间','使用结束时间','金额','备注']
      this.searchLoading = true
      this.parkingChargeService.find(new ParkingChargeQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1 || !resp.data || resp.data.list.length < 1) {
            this.message.error('无数据导出')
            return
          }
          const exportData = []
          for (const d of resp.data.list) {
            exportData.push([d.parkingAreaNumber,d.residentRoomNumber,d.licensePlate,d.billingStartDate,d.billingEndDate,d.amount,d.remark])
          }
          exportToExcel(headers, exportData)
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  editRow(id: number) {
    this.parkingChargeAddComponent.display(id)
  }

  delRow(id: number) {
    this.modal.confirm({
      nzTitle: '<i>删除提示</i>',
      nzContent: '<b>确定要删除吗?</b>',
      nzOnOk: () => {
        this.parkingChargeService.del(id).subscribe({
          next: (resp) => {
            if (resp && resp.code === 1) {
              this.message.success('删除成功!')
              this.onSearch()
            } else {
              this.message.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
            }
          },
          complete: () => {
            this.searchLoading = false
          }
        })
      }
    });
  }

  detailRow(record: ParkingCharge) {
    this.parkingChargeViewComponent.display(record)
  }

  findParkingArea() {
    this.parkingAreaSelectorComponent.display()
  }

  handleParkingAreaSelectedEvent(selectedParkingArea: { parkingAreaId?: number; parkingAreaNumber?: string; }) {
    if (selectedParkingArea && 'parkingAreaId' in selectedParkingArea) {
      this.searchForm.patchValue(selectedParkingArea);
    }
  }

  findRoom() {
    this.roomSelectorComponent.display()
  }

  handleRoomSelectedEvent(selectedRoom: { residentRoomId?: number; residentRoomNumber?: string; }) {
    if (selectedRoom && 'residentRoomId' in selectedRoom) {
      this.searchForm.patchValue(selectedRoom);
    }
  }

  onAdded(addedFlag: boolean) {
    if (addedFlag) {
      this.onSearch()
    }
  }
}
